<template>
    <div>
        <el-steps :active="state.active" align-center>
            <el-step title="项目基本信息" />
            <el-step title="完成" />
        </el-steps>
        <el-form v-if="!state.success" :model="formInline" ref="formInlineRef" :rules="projectRules" class="demo-form-inline"
                 label-width="120px">
            <div class="twoline">
                <el-form-item label="项目集名称" prop="projectSetName">
                    <el-input :disabled="getURLhandler(route.path).type > 1" v-model="formInline.projectSetName"
                              placeholder="项目集名称" />
                </el-form-item>
                <el-form-item label="项目(可多选)" class="oneline" prop="">
                    <el-select v-model="formInline.projects" clearable class="select_project" multiple collapse-tags-tooltip
                               collapse-tags placeholder="请选择项目" @change="changeProject" :disabled="getURLhandler(route.path).type > 1">
                        <el-option v-for="item in state.projectOptionsArr" :key="item.projectId" :label="item.projectName"
                                   :value="item.projectId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="项目集归属" prop="belongId">
                    <el-select v-model="formInline.belongId" :disabled="getURLhandler(route.path).pid" clearable>
                        <el-option v-for="item in state.projectSetBelongList" :key="item.projectSetBelongId" :label="item.projectSetBelongName" :value="item.projectSetBelongId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="项目集编码" prop="projectSetCode">
                    <el-input :disabled="getURLhandler(route.path).type > 1" v-model.number="formInline.projectSetCode"
                              placeholder="编号" />
                </el-form-item>
            </div>
            <div class="twoline">
                <!-- <el-form-item label="项目位置" prop="address">
                  <el-input v-model="formInline.address" placeholder="项目位置">
                    <template #append
                      ><svg-icon
                        icon-class="map-icon"
                        style="cursor: pointer"
                        class="refresh-icon m-l10"
                        @click="mapclick"
                    /></template>
                  </el-input>
                </el-form-item> -->
                <!--
                <el-form-item label="所属街道" prop="streetCode">
                  <el-select
                    v-model="formInline.regionCode"
                    clearable
                    placeholder="请选择区域"
                    @change="areaTypeChange"
                  >
                    <el-option
                      v-for="item in state.areaTypeOptionsArr"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                  <el-select
                    v-model="formInline.streetCode"
                    clearable
                    placeholder="请选择街道"
                    @change="streerTypeChange"
                  >
                    <el-option
                      v-for="item in state.streerTypeOptionsArr"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    />
                  </el-select>
                </el-form-item> -->
            </div>
            <div class="oneline"></div>

            <el-form-item label="备注" class="oneline" prop="remark">
                <el-input v-model="formInline.remark" show-word-limit :disabled="getURLhandler(route.path).type > 1"
                          type="textarea" />
            </el-form-item>
        </el-form>

        <div class="buttons" v-if="!state.success">
            <el-button @click="goback" class="button_cancel2">取消</el-button>
            <el-button type="primary" v-if="!(getURLhandler(route.path).type > 1)" @click="submitHandler(formInlineRef)" class="button_view">
                确定
            </el-button>
        </div>
        <div v-if="state.success">
            <p style="height: 40px">
                <svg-icon icon-class="sucesss-icon" style="width: 100%; height: 100%"></svg-icon>
            </p>
            <p style="font-size: '16px'; text-align: center">
                {{ `恭喜您，完成项目集的${route.query.type ? '编辑' : '添加'}!` }}
            </p>
            <p style="font-size: '16px'; text-align: center">
                <el-button @click="goback">返回列表页</el-button>
            </p>
        </div>

        <mapDialog ref="mapdialog" @getMapAddrInfo="getMapAddrInfo"></mapDialog>
    </div>
</template>
<script setup>
import { getURLhandler } from '@/views/constructionProjectManage/static/utools.js'


import MapDialog from './mapDialog.vue'
import { ref, reactive, onMounted, computed } from 'vue'
import { assetsApi } from '@/api/assets'
import { useRouter, useRoute } from 'vue-router'
import { projectApi, projectListApi } from '@/api/project'
import {
    ElTag,
    ElForm,
    ElSelect,
    ElFormItem,
    ElStep,
    ElSteps
} from 'element-plus'

const state = reactive({
    streerTypeOptionsArr: [],
    areaTypeOptionsArr: [],
    projectOptionsArr: [], //所有项目
    editId: '', //编辑时ID
    active: 1,
    success: false, //编辑或添加是否成功
    type: 0, //0新增 1编辑
    projectSetBelongList:[]
})
let centerDialogVisible = ref(false)
let formInlineRef = ref(null)
const formInline = reactive({
    projects: [],
    address: '',

    remark: ''
})
//路由跳转
let router = useRouter()
let route = useRoute()

//判断是否编辑
let isUpdate = computed(() => {
    if (getURLhandler(route.path).type == 1) {
        return true
    } else {
        return false
    }
})
const projectRules = reactive({
    projectSetName: [
        { required: true, message: '项目集名称不能为空', trigger: 'blur' }
    ],
    /*  belongId: [
          { required: true, message: '项目集归属不能为空', trigger: 'change' }
      ],*/
    projectSetCode: [
        { required: true, message: '编号不能为空', trigger: 'blur' }
    ],
    address: [{ required: true, message: '项目位置不能为空', trigger: 'blur' }],
    streetCode: [
        { required: true, message: '所属街道不能为空', trigger: 'blur' }
    ],
    projects: [{ required: true, message: '项目不能为空', trigger: 'blur' }],
    remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
})

const getMapAddrInfo = (data) => {
    formInline.address = data.address
}

// 初始化获取区域
const initAreaOptions = (type, cd) => {
    assetsApi.getLocations(type, cd).then((res) => {
        const { code, data, msg } = res
        if (code == 200) {
            if (cd) {
                state.streerTypeOptionsArr = data
            } else {
                state.areaTypeOptionsArr = data
            }
        }
    })
}
//获取所有项目信息
const projectListApiHandler = (id = '') => {
    projectListApi.getAllList(id || '').then((res) => {
        const { code, data, msg } = res
        if (code == 200) {
            state.projectOptionsArr = data
        }
    })
}

//项目多选下拉变化
const changeProject = (val) => {
    console.log(val)
}
//提交
const submitHandler = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            let submitObj = JSON.parse(JSON.stringify(formInline))
            let projects = []
            submitObj.projects.forEach((item) => {
                let itemObj = state.projectOptionsArr.filter(
                    (e) => e.projectId == item
                )[0]

                projects.push(itemObj)
            })
            submitObj.projects = projects
            submitObj.projectSetId = submitObj.projectSetId + ''
            if (
                getURLhandler(route.path).edit &&
                getURLhandler(route.path).type == 1
            ) {
                //编辑提交
                projectApi.editProjects(submitObj).then((res) => {
                    const { code, data, msg } = res
                    if (code === '200') {
                        state.success = true
                        state.active = 2
                    }
                })
            } else {
                delete submitObj.projectSetId
                if(getURLhandler(route.path).pid){
                    submitObj.pid =  getURLhandler(route.path).pid;
                }
                //新增提交
                projectApi.addProjects(submitObj).then((res) => {
                    const { code, data, msg } = res
                    if (code === '200') {
                        state.success = true
                        state.active = 2
                    }
                })
            }
        }
    })
}

//返回列表页
const goback = () => {
    router.push({
        path: '/constructionProjectManage/projectmanagement/index'
    })
}

//通过ID获取详情
const getByidHandler = async (id) => {
    await projectApi.getByidProjects(id).then((res) => {
        const { code, data, msg } = res
        if (code === '200') {
            if (data?.projects) {
                let arr = []
                data.projects.forEach((item) => {
                    arr.push(item.projectId)
                })
                data.projects = arr
            }

            // initAreaOptions(2, data.regionCode);
            setTimeout(() => {
                Object.assign(formInline, data)
            }, 0)
        }
    })
}

const getProjectSetBelong = () => {
    projectApi.getProjectSetBelong().then(res=>{
        if(res.code === '200'){
            state.projectSetBelongList = res.data;
        }
    })
}

defineExpose({
    centerDialogVisible,
    state
})
onMounted(() => {
    // initAreaOptions(1); //获取区域街道信息
    projectListApiHandler()

    if (getURLhandler(route.path).type > 0) {
        //编辑
        getByidHandler(getURLhandler(route.path).edit)
    }

    getProjectSetBelong();
    if(getURLhandler(route.path).pid){
        formInline.belongId = getURLhandler(route.path).projectSetBelongId.toString();
    }
})
</script>
<style lang="scss" scoped>
.demo-form-inline {
  margin-top: 32px;
  margin-bottom: 20px;
  border: 1px solid #E3E7F1;
  padding: 15px;
  border-radius: 10px;
}

.el-select {
  width: 100% !important;
}

.select_project {
  width: 100%;
}

.buttons {
  text-align: center;
}

.twoline {
  display: flex;

  .el-form-item {
    width: 100%;
    display: flex;
    justify-content: space-between;

    .el-select {
      width: 50%;
    }
  }

  justify-content: space-between;
}

@import '@/assets/general_style/dialog.scss';
</style>

<style lang="scss" scoped>
:deep(.el-steps) {
  .el-step__title.is-process,
  is-text {
    font-weight: normal !important;
    color: #a8abb2 !important;
  }

  .is-process {
    border-color: #a8abb2 !important;
  }

  .el-step__head.is-process {
    font-weight: normal !important;
    color: #a8abb2 !important;
  }
}
</style>
